<template>
  <el-dialog
      :title="props.type == 'add' ? '添加分类' : '修改分类'"
      v-model="state.visible"
      width="400px"
      @close="clear"
      @open="show"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="养老院名字" prop="name">
        <el-input type="text" v-model="state.ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="养老院封面">
        <el-upload
            :action="uploadImgServer"
            :on-success="handleUrlSuccess"
            list-type="picture"
            :auto-upload="true"
            :show-file-list="false"
        >
          <img v-if="state.ruleForm.image" :src="state.ruleForm.image" class="cover" alt="封面"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <div id="editor"></div>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input type="text" v-model="state.ruleForm.price"></el-input>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input type="text" v-model="state.ruleForm.address"></el-input>
      </el-form-item>

      <el-form-item label="标签" prop="tag">
        <el-input type="text" v-model="state.ruleForm.tags"></el-input>
      </el-form-item>

      <el-form-item label="床位" prop="bed">
        <el-input type="text" v-model="state.ruleForm.beds"></el-input>
      </el-form-item>

      <el-form-item label="性质" prop="nature">
        <el-input type="text" v-model="state.ruleForm.nature"></el-input>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-input type="text" v-model="state.ruleForm.type"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import {addNursingHome, updateNursingHome, getNursingHomeById} from '../service/nursingHomeApi.js'
import {uploadImgServer} from "../store/index.js"
import {ElMessage} from 'element-plus'
import {fileUpload} from '../service/minioFileApi.js'
import E from 'wangeditor'
const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})
const formRef = ref(null)
const route = useRoute()
const filelist = ref([])
const state = reactive({

  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    name: '',
    image: '',
    price: '',
    address: '',
    tags: '',
    beds: '',
    nature: '',
    type: '',
    content:''
  },
  rules: {

    name: [
      {required: true, message: '名称不能为空', trigger: ['change']}
    ],
    image: [
      {required: true, message: '图片不能为空', trigger: ['change']}
    ],
    price: [
      {required: true, message: '价格不能为空', trigger: ['change']}
    ],
    address: [
      {required: true, message: '地址不能为空', trigger: ['change']}
    ],

    tags: [
      {required: true, message: '标签不能为空', trigger: ['change']}
    ],
    beds: [
      {required: true, message: '床位不能为空', trigger: ['change']}
    ],
    nature: [
      {required: true, message: '性质不能为空', trigger: ['change']}
    ],
    type: [
      {required: true, message: '类型不能为空', trigger: ['change']}
    ]
  },
})

const clear = () => {
  state.editor.destroy()
}

const show = () => {
  // 富文本编辑器实例创建

  state.editor = new E('#editor')
  //配置上传地址

  // 配置服务器端地址
  state.editor.config.uploadImgServer = uploadImgServer
  state.editor.config.uploadFileName = 'file'
  state.editor.config.uploadImgHooks = {
    customInsert: (insertImgFn, result) => {

      const imgUrl = result.data;
      insertImgFn(imgUrl); // 插入图片
    },
    // 可选：错误处理
    error: (error) => {
      console.error('上传失败:', error);
    }
  };
  // state.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
  //   const response = await fileUpload(resultFiles[0]);
  //   insertImgFn(response.data)
  // }
  state.editor.config.menus = [
    // 菜单配置
    'head', // 标题
    'bold', // 粗体
    'italic', // 斜体
    'underline', // 下划线
    'link', // 插入链接
    'image', // 插入图片
    'undo', // 撤销
    'redo' // 重复
  ]
  state.editor.create()

}
// 获取详情
const getDetail = async (id) => {
  const result = await getNursingHomeById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    name: result.data.name,
    image: result.data.image,
    price: result.data.price,
    address: result.data.address,
    tags: result.data.tags,
    beds: result.data.beds,
    nature: result.data.nature,
    type: result.data.type,
    content:result.data.content
  }
  if (state.editor != null) {
    state.editor.txt.html(result.data.content)
  }
}
//删除上传图片
const handleRemove = (file, fileList) => {
  state.ruleForm.image = ''
}
//上传成功
const handleUrlSuccess = (res) => {
  state.ruleForm.image = res.data
}

// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.ruleForm.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const {level = 1, parent_id = 0} = route.query
    state.ruleForm = {
      id: '',
      name: '',
      image: '',
      price: '',
      address: '',
      tags: '',
      beds: '',
      nature: '',
      type: '',
      content:''
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }
}
// 关闭弹窗
const close = () => {
  state.visible = false
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        state.ruleForm.content = state.editor.txt.html()
        // 添加方法
        await addNursingHome(state.ruleForm).then(() => {
          ElMessage.success('添加成功')
          close()
          if (props.reload) props.reload()
        })
      } else {
        state.ruleForm.content = state.editor.txt.html()
        // 修改方法
        await updateNursingHome(state.ruleForm).then(() => {
          ElMessage.success('修改成功')
          close()
          if (props.reload) props.reload()
        })
      }
    }
  })
}
defineExpose({open, close})
</script>

<style scoped>
.el-upload__tip {
  float: left;
}

.cover {
  border: 1px solid #FFFFFF;
  border-radius: 10px;
  width: 80px;
  height: 80px;
}
</style>